/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.datasource.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.entity.ActionDataSourceVo;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.meta.service.datasource.DataSourceExecuteService;
import org.apache.servicecomb.provider.springmvc.reference.RestTemplateBuilder;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Service("dataSourceActionExecuteService")
public class DataSourceActionExecuteServiceImpl implements DataSourceExecuteService {

    private String URL_TEMPLATE="cse://%s%s?%s";

    @Override
    public List<Map<String, Object>> execute(DynaBean dataSource, String parameterStr, String limit) {
        JSONObject configJson = JSON.parseObject(dataSource.getStr("DATASOURCE_CONFIG"));
        String productCode = dataSource.getStr("SY_PRODUCT_CODE");
        String urlConfig = configJson.getString("apiUrl");
        ActionDataSourceVo actionDataSourceVo = new ActionDataSourceVo();
        actionDataSourceVo.setParameterStr(parameterStr);
        actionDataSourceVo.setLimit(StringUtil.isNotEmpty(limit)?Integer.parseInt(limit):0);
        actionDataSourceVo.setFieldConfig(configJson.getString("fieldName"));
        actionDataSourceVo.setParameterConfig(configJson.getString("paramName"));
        RestTemplate restTemplate = RestTemplateBuilder.create();
        String url = buildUrl(productCode,urlConfig,actionDataSourceVo);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<ActionDataSourceVo> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Map> result=null;
        List<Map<String,Object>> mapList=null;
        try{
             result = restTemplate.postForEntity(url,httpEntity,Map.class);
             mapList = (List<Map<String, Object>>) result.getBody();
            if( !HttpStatus.OK.name().equals(result.getStatusCode().name()) ){
                throw new PlatformException(MessageUtils.getMessage("dataSource.action.error"), PlatformExceptionEnum.UNKOWN_ERROR);
            }
        }catch (InvocationException e){
            if(e.getStatusCode()==404){
                throw new PlatformException(MessageUtils.getMessage("dataSource.url.notFound"), PlatformExceptionEnum.UNKOWN_ERROR);
            }
        }
        return mapList;
    }

    @Override
    public List<DynaBean> executeForRpc(DynaBean dataSource, Map<String, Object> map, int limit) {
        JSONObject configJson = JSON.parseObject(dataSource.getStr("DATASOURCE_CONFIG"));
        String productCode = dataSource.getStr("SY_PRODUCT_CODE");
        String urlConfig = configJson.getString("apiUrl");
        ActionDataSourceVo actionDataSourceVo = new ActionDataSourceVo();
        actionDataSourceVo.setParameterStr(JSON.toJSONString(map));
        actionDataSourceVo.setLimit(limit);
        actionDataSourceVo.setFieldConfig(configJson.getString("fieldName"));
        actionDataSourceVo.setParameterConfig(configJson.getString("paramName"));
        RestTemplate restTemplate = RestTemplateBuilder.create();
        String url = buildUrl(productCode,urlConfig,actionDataSourceVo);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<ActionDataSourceVo> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<Map> result = restTemplate.postForEntity(url,httpEntity,Map.class);
        if( !HttpStatus.OK.name().equals(result.getStatusCode().name()) ){
            throw new PlatformException(MessageUtils.getMessage("dataSource.action.error"), PlatformExceptionEnum.UNKOWN_ERROR);
        }
        List<DynaBean> mapList = (List<DynaBean>) result.getBody();
        return mapList;
    }

    private String buildUrl(String productCode, String urlConfig, ActionDataSourceVo actionDataSourceVo) {
        long limit = actionDataSourceVo.getLimit();
        String parameterStr = actionDataSourceVo.getParameterStr();
        String fieldConfig = actionDataSourceVo.getFieldConfig();
        String parameterConfig = actionDataSourceVo.getParameterConfig();
        if(StringUtil.isEmpty(parameterStr)||" ".equals(parameterStr)){
            parameterStr="";
        }
        if(StringUtil.isNotEmpty(parameterStr)){
            parameterStr =  URLEncoder.encode(parameterStr);
        }
        if(StringUtil.isNotEmpty(fieldConfig)){
            fieldConfig = URLEncoder.encode(fieldConfig);
        }
        if(StringUtil.isNotEmpty(parameterConfig)){
            parameterConfig = URLEncoder.encode(parameterConfig);
        }
        String par = "parameterStr="+parameterStr+"&limit="+limit+"&fieldConfig="+fieldConfig+"&parameterConfig="+parameterConfig;
        return String.format(URL_TEMPLATE,productCode,urlConfig,par);
    }
}
